<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库位编号" prop="locationCode">
        <el-input
          v-model="queryParams.locationCode"
          placeholder="请输入库位编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位名称" prop="locationName">
        <el-input
          v-model="queryParams.locationName"
          placeholder="请输入库位名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属仓库" prop="warehouseId">
        <el-select
          v-model="queryParams.warehouseId"
          placeholder="请选择产品"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in warehouseOptions" 
            :key="item.warehouseId"
            :label="item.warehouseName"
            :value="item.warehouseId"
          />
        </el-select>
      </el-form-item> 
      <el-form-item label="库位类型" prop="locationType">
        <el-select v-model="queryParams.locationType" placeholder="请选择库位类型" clearable>
          <el-option
            v-for="dict in location_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="容量" prop="capacity">
        <el-input
          v-model="queryParams.capacity"
          placeholder="请输入容量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="已用容量" prop="usedCapacity">
        <el-input
          v-model="queryParams.usedCapacity"
          placeholder="请输入已用容量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in wms_location_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['wms:location:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:location:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:location:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['wms:location:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="locationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库位ID" align="center" prop="locationId" />
      <el-table-column label="库位编号" align="center" prop="locationCode" />
      <el-table-column label="库位名称" align="center" prop="locationName" />
      <el-table-column label="所属仓库" align="center" prop="warehouseName" />
      <el-table-column label="库位类型" align="center" prop="locationType">
        <template #default="scope">
          <dict-tag :options="location_type" :value="scope.row.locationType"/>
        </template>
      </el-table-column>
      <el-table-column label="容量" align="center" prop="capacity" />
      <el-table-column label="已用容量" align="center" prop="usedCapacity" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wms_location_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wms:location:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wms:location:remove']">删除</el-button>
          <el-button link type="primary" icon="View" @click="handleViewInventory(scope.row)" v-hasPermi="['wms:location:query']">查看库存</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库库位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="locationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库位编号" prop="locationCode">
          <el-input v-model="form.locationCode" placeholder="请输入库位编号" />
        </el-form-item>
        <el-form-item label="库位名称" prop="locationName">
          <el-input v-model="form.locationName" placeholder="请输入库位名称" />
        </el-form-item>
        <el-form-item label="所属仓库" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择所属仓库">
            <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库位类型" prop="locationType">
          <el-select v-model="form.locationType" placeholder="请选择库位类型">
            <el-option
              v-for="dict in location_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入容量" />
        </el-form-item>
        <el-form-item label="已用容量" prop="usedCapacity">
          <el-input v-model="form.usedCapacity" placeholder="请输入已用容量" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in wms_location_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 库存列表对话框 -->
    <el-dialog title="库位库存列表" v-model="inventoryDialogVisible" width="800px" append-to-body>
      <div v-if="currentLocation">
        <div class="location-info">
          <h3>{{ currentLocation.locationName }} - 库存信息</h3>
          <p>所属仓库: {{ currentLocation.warehouseName }}</p>
        </div>
        
        <el-table v-loading="inventoryLoading" :data="locationInventories" style="width: 100%">
          <el-table-column label="库存ID" align="center" prop="inventoryId" />
          <el-table-column label="物料" align="center" prop="materialName" />
          <el-table-column label="物料编码" align="center" prop="materialCode" />
          <el-table-column label="规格型号" align="center" prop="specification" />
          <el-table-column label="库存数量" align="center" prop="quantity" />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="mwm_inventory_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="empty-block" v-if="locationInventories.length === 0">
          <el-empty description="该库位下暂无库存" />
        </div>
        
        <pagination
          v-show="inventoryTotal>0"
          :total="inventoryTotal"
          v-model:page="inventoryQueryParams.pageNum"
          v-model:limit="inventoryQueryParams.pageSize"
          @pagination="loadLocationInventories"
        />
        
        <div class="dialog-footer" style="margin-top: 20px; text-align: right;">
          <el-button @click="inventoryDialogVisible = false">关闭</el-button>
          <!-- <el-button type="primary" @click="handleAddInventory" v-hasPermi="['mwm:inventory:add']">添加库存</el-button> -->
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Location">
import { listLocation, getLocation, delLocation, addLocation, updateLocation, listWarehouse } from "@/api/wms/location";
import { listInventory } from "@/api/mwm/inventory";

const { proxy } = getCurrentInstance();
// 加载字典数据
const dictData = proxy.useDict('wms_location_status', 'location_type', 'mwm_inventory_status');
const wms_location_status = dictData.wms_location_status;
const location_type = dictData.location_type;
const mwm_inventory_status = dictData.mwm_inventory_status;

const locationList = ref([]);
const warehouseOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 库存相关变量
const inventoryDialogVisible = ref(false);
const locationInventories = ref([]);
const currentLocation = ref(null);
const inventoryLoading = ref(false);
const inventoryTotal = ref(0);
const inventoryQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  locationId: null
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    locationCode: null,
    locationName: null,
    warehouseId: null,
    locationType: null,
    capacity: null,
    usedCapacity: null,
    status: null,
  },
  rules: {
    locationCode: [
      { required: true, message: "库位编号不能为空", trigger: "blur" }
    ],
    warehouseId: [
      { required: true, message: "所属仓库ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询仓库库位列表 */
function getList() {
  loading.value = true;
  listLocation(queryParams.value).then(response => {
    locationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    locationId: null,
    locationCode: null,
    locationName: null,
    warehouseId: null,
    locationType: null,
    capacity: null,
    usedCapacity: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("locationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.locationId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加仓库库位";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _locationId = row.locationId || ids.value
  getLocation(_locationId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改仓库库位";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["locationRef"].validate(valid => {
    if (valid) {
      if (form.value.locationId != null) {
        updateLocation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLocation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _locationIds = row.locationId || ids.value;
  proxy.$modal.confirm('是否确认删除仓库库位编号为"' + _locationIds + '"的数据项？').then(function() {
    return delLocation(_locationIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wms/location/export', {
    ...queryParams.value
  }, `location_${new Date().getTime()}.xlsx`)
}

/** 查看库存按钮操作 */
function handleViewInventory(row) {
  currentLocation.value = row;
  inventoryDialogVisible.value = true;
  inventoryQueryParams.locationId = row.locationId;
  inventoryQueryParams.pageNum = 1; // 重置为第一页
  loadLocationInventories();
}

/** 加载库位下的库存 */
function loadLocationInventories() {
  inventoryLoading.value = true;
  listInventory(inventoryQueryParams).then(response => {
    locationInventories.value = response.rows || [];
    inventoryTotal.value = response.total;
    inventoryLoading.value = false;
  }).catch(() => {
    inventoryLoading.value = false;
  });
}

/** 添加库存按钮操作 */
/* function handleAddInventory() {
  // 跳转到库存管理页面，并带上当前库位ID和仓库ID
  proxy.$router.push({
    path: '/mwm/inventory',
    query: { 
      locationId: currentLocation.value.locationId,
      warehouseId: currentLocation.value.warehouseId
    }
  });
  inventoryDialogVisible.value = false;
} */



// 在组件挂载时获取数据
onMounted(() => {
 // 获取所属仓库（不分页）列表
 listWarehouse().then(response => {
  warehouseOptions.value = response.data || response.rows; 
 });
getList(); // 原有的获取计划列表
});

</script>

<style scoped>
.location-info {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  margin-bottom: 15px;
}

.location-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.location-info p {
  margin: 5px 0;
}

.mb-20 {
  margin-bottom: 20px;
}

.empty-block {
  margin: 20px 0;
}
</style>
